<?php
/*
 * 
 * PAGE DES META BOX
 * 
 */

/*
 * Meta box JAUGE
 */
function wpspo_metabox_admin_menu() {
    add_meta_box('wpspo_boxprojets',__('Options for this project', 'sponsorpress'), 'wpspo_meta_box', 'projet', 'side', 'high');
}
add_action( 'admin_menu', 'wpspo_metabox_admin_menu' );

function wpspo_meta_box(){
    
    global $post;

    $valueObjectif = get_post_meta($post->ID, 'wpspo_boxprojets', true); // Récupère l'objectif cible
    $projetArchive = get_post_status( $post->ID ); // Récupère le status du post
    if($projetArchive=='archive') {
        echo '<div style="text-align:center;background-color:#cc0000;color:#ffffff;padding:5px;margin-bottom:5px">'.__('This project has been archived', 'sponsorpress').'</div>';
    }

    echo '<label for="wpspo_boxprojets">'.__('Budget to find:', 'sponsorpress').'</label><input type="text" name="wpspo_boxprojets" tabindex="8" id="wpspo_boxprojets" size="4" value="'.$valueObjectif.'">'.get_wpspo_currency_symbol().'<hr />';

    echo __('End project date:', 'sponsorpress');
    $dateProjet = date("d-m-Y", mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1));
    if(get_post_meta($post->ID, 'wpspo_boxdateend', true) =='') { $print_dateProjet = $dateProjet; } else { $print_dateProjet = get_post_meta($post->ID, 'wpspo_boxdateend', true); }
    echo '<input type="text" id="wpspo_boxdateend" name="wpspo_boxdateend" size="8" value="'.$print_dateProjet.'"/>';
    echo '<script type="text/javascript">';
    echo "
        jQuery(document).ready(function() {
            jQuery('#wpspo_boxdateend').datepicker({
                dateFormat : 'dd-mm-yy'
            });
        });

        </script>";
    if(get_post_meta($post->ID, 'wpspo_boxnodate', true) == 1) { $bCheck2 = 'checked'; } else { $bCheck2 = ''; }
    echo '<br /><label for"wpspo_boxnodate">'.__('No end date?', 'sponsorpress').'</label> <input type="checkbox" name="wpspo_boxnodate" id="wpspo_boxnodate" value="1" '.$bCheck2.' />';
    
    
    $textProjet = get_post_meta($post->ID, 'wpspo_boxtexte', true);
    echo '<hr />'.__( 'Text:', 'sponsorpress' ).'<br />';
    echo '<small>'.__('Insert %COL% to display the total collected, %OBJ% to display the project objective and %SA% for newline.', 'sponsorpress').'</small>';
    echo '<textarea class="widefat" id="wpspo_boxtexte" name="wpspo_boxtexte">'.esc_attr( $textProjet ).'</textarea>';
    $linkDonate = get_post_meta($post->ID, 'wpspo_boxlinkdonate', true); // Récupère le lien pour donner
    echo '<hr /><label for"wpspo_boxlinkdonate">'.__( 'Link to donate:', 'sponsorpress' ).'</label><br />';
    echo '<input type="text" name="wpspo_boxlinkdonate" id="wpspo_boxlinkdonate" value="'.$linkDonate.'" />';
}

function wpspo_metabox_save_postdata( $post_id ) {

    // vérification des droits permissions
    if ( 'page' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
    } else {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
    }
    //ajouter éventuellement des vérifications pour les custom post types
    if(isset($_POST['wpspo_boxprojets'])) { update_post_meta($post_id, 'wpspo_boxprojets', $_POST['wpspo_boxprojets']); }
    update_post_meta($post_id, 'wpspo_boxnodate', $_POST['wpspo_boxnodate']);
    if(isset($_POST['wpspo_boxdateend'])) { update_post_meta($post_id, 'wpspo_boxdateend', $_POST['wpspo_boxdateend']); }
    update_post_meta($post_id, 'wpspo_boxtexte', $_POST['wpspo_boxtexte']);
    update_post_meta($post_id, 'wpspo_boxlinkdonate', $_POST['wpspo_boxlinkdonate']);
    //paramètres : id du post, nom du champ perso, valeur (en post)

}
add_action( 'save_post', 'wpspo_metabox_save_postdata' );


/*
 * Meta box PROJETS -> DEFIS
 */
function wpspo_metabox_admin_defis() {
    add_meta_box('wpspo_boxprojets',__('Options', 'sponsorpress'), 'wpspo_meta_box_projets', 'defi', 'side', 'high');
}
add_action( 'admin_menu', 'wpspo_metabox_admin_defis' );


function wpspo_meta_box_projets(){
    
    global $post;  
    global $wpdb;
    global $typenow;
    
    $totalPromesse = WPSPO_Promesse::get_countByDefi($post->ID);
    
    /* On va chercher les infos du défi */
    $data = WPSPO_defis::get_options($post->ID);
    $valueOptions = json_decode($data->defis_option_value);

    echo __('Sum found for this challenge:', 'sponsorpress').' <div style="text-align:center;font-size:25px;padding:5px;">'.$totalPromesse.''.get_wpspo_currency_symbol().'</div><hr />';
    
    $typeSelected = get_post_meta($post->ID, 'wpspo_typedefi', true);
    echo __('Type:', 'sponsorpress').'<br />';
    echo '<select name="type_defis" id="type_defis" class="wpspo-select">';
            $listTypeDefi = wpspo_type_defi();
            //print_r($listTypeDefi);
            foreach ($listTypeDefi as $name => $nb) {
                if($typeSelected==$nb) { $add = 'selected';} 
                echo '<option value="'.$nb.'" '.$add.'>'.$name.'</option>
                ';
            }
    echo '</select>';
    
    /* Requête pour aller chercher les post-type des projets */
    $args = array( 'post_type' => 'projet', 'posts_per_page' => 10, 'post_status' => 'publish' );  
    $loop = new WP_Query( $args );
    
    $idSelected = get_post_meta($post->ID, 'wpspo_choixprojets', true) ;
    
    if($loop->have_posts() ) {
        
        
        
        echo '<br />Projet :<br /><SELECT name="wpspo_choixprojets">';
        echo '<OPTION VALUE="#">'.__('Choose your project', 'sponsorpress').'</OPTION>';
        while ( $loop->have_posts() ) : $loop->the_post();
                        
            echo '<OPTION VALUE="'.get_the_ID().'"';
            if($idSelected == get_the_ID()) { echo 'selected="selected"'; }
            echo '>'.get_the_title().'</OPTION>';
            
        endwhile; 
        echo '</SELECT><hr />'; 
    } else {
        
        _e('Currently, there is no project', 'sponsorpress');
    }
        

        $dateDefi = $valueOptions->date_defis;
        $dateEndDefi = $valueOptions->date_end_defis;
        $typeDefis = $valueOptions->type_defis;
        $modeDefi  = $valueOptions->mode_defis;
        $modetextDefi  = stripslashes(trim($valueOptions->text_mode_defis));
        $coordDefis = $valueOptions->coord_defis;
        $recupLatLngDefi = explode("##", $coordDefis);
        $latDefis = $recupLatLngDefi[0];
        $lngDefis = $recupLatLngDefi[1];
        

        echo __('Start Date:', 'sponsorpress').' <input type="text" size="9" id="datepicker" name="date_defis" size="8" value="'.$dateDefi.'" />';
        echo '<br />'.__('End Date:', 'sponsorpress').' <input type="text" size="9" id="datepicker" name="date_end_defis" size="8" value="'.$dateEndDefi.'" /><hr />';

        echo __('Method of calculation donations', 'sponsorpress').'<br />';
        if($modeDefi==1) { $checkedMode = 'checked'; } else { $checkedMode = ''; }
        echo '<input type="radio" id="mode_defis" name="mode_defis" value="1" '.$checkedMode.' /> '.get_wpspo_currency_symbol().' / ';
        echo '<input type="text" name="text_mode_defis" id="text_mode_defis" value="'.$modetextDefi.'" /><br />';
        if($modeDefi==2) { $checkedDefi = 'checked'; } else { $checkedDefi = ''; }
        echo '<input type="radio" id="mode_defis" name="mode_defis" value="2" '.$checkedDefi.' /> Don fixe';
        echo '<input type="hidden" name="villeDefi" value="'.stripslashes(trim($valueOptions->ville_defis)).'" />';
        echo '<input type="hidden" name="coordonnees" value="'.$latDefis.'##'.$lngDefis.'" />';
        echo '<input type="hidden" name="shareDefi" value="'.$valueOptions->share_defis.'" />';
        echo '<input type="hidden" name="sharePrive" value="'.$valueOptions->share_prive.'" />';
        echo '<input type="hidden" name="clePrive" value="'.$valueOptions->cle_defis.'" />';   
    
}

function wpspo_metabox_save_defis( $post_id ) {
    // ne rien faire en auto-save
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;

    // vérification des droits permissions
    if ( 'page' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
    } else {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
    }
    //ajouter éventuellement des vérifications pour les custom post types
    if(isset($_POST['wpspo_choixprojets'])) { update_post_meta($post_id, 'wpspo_choixprojets', $_POST['wpspo_choixprojets']); }
    if(isset($_POST['type_defis'])) { update_post_meta($post_id, 'wpspo_typedefi', $_POST['type_defis']); }
    // On construit les options
    $arrayOptions = array(
        'date_defis' => $_POST['date_defis'],
        'date_end_defis' => $_POST['date_end_defis'],
        'mode_defis' => $_POST['mode_defis'],
        'text_mode_defis' => $_POST['text_mode_defis'],
        'type_defis' => $_POST['typeDefis'],
        'coord_defis' => $_POST['coordonnees'],
        'type_defis' => $_POST['typeDefis'],
        'share_defis' => $_POST['shareDefi'],
        'share_prive' => $_POST['sharePrive'],
        'cle_defis' => $_POST['clePrive'],
        'ville_defis' => $_POST['villeDefi']
    );
    $dataJson = json_encode($arrayOptions);
    $insertOptions = WPSPO_Defis::updateOptions($_POST["wpspo_choixprojets"], $post_id, $dataJson, 1);

}
add_action( 'save_post', 'wpspo_metabox_save_defis' );


